<script setup>
import { ref, onMounted, onUnmounted, watch, computed } from 'vue'
import api from '@/api/request'
import { Promotion } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/useUserStore'

const userStore = useUserStore()
const wsConnection = ref(null)
const isConnected = ref(false)
const reconnectAttempts = ref(0)
const maxReconnectAttempts = 5
const heartbeatInterval = ref(null)
const reconnectTimeout = ref(null)

// 存储消息数组
const messages = ref([])

// 用于输入新消息
const newMessage = ref('')

// 添加团队成员列表
const teamMembers = ref([])

// 选中的成员ID列表
const selectedMemberIds = ref([])

// 全选状态
const selectAll = ref(false)

// 添加搜索查询
const searchQuery = ref('')

// 存储每个用户的消息数量
const userMessageCounts = ref({})

// 过滤后的用户列表
const filteredTeamMembers = computed(() => {
  if (!searchQuery.value) return teamMembers.value
  return teamMembers.value.filter((member) =>
    member.name.toLowerCase().includes(searchQuery.value.toLowerCase())
  )
})

// 更新用户消息计数
const updateUserMessageCount = (userId) => {
  if (!userMessageCounts.value[userId]) {
    userMessageCounts.value[userId] = 0
  }
  userMessageCounts.value[userId]++
}

// 发送心跳包
const sendHeartbeat = () => {
  if (wsConnection.value && wsConnection.value.readyState === WebSocket.OPEN) {
    try {
      wsConnection.value.send(JSON.stringify({ type: 'heartbeat' }))
      console.log('心跳包发送成功')
    } catch (error) {
      console.error('发送心跳包失败:', error)
      // 如果发送心跳包失败，尝试重新连接
      handleReconnect()
    }
  }
}

// 处理重连逻辑
const handleReconnect = () => {
  if (reconnectTimeout.value) {
    clearTimeout(reconnectTimeout.value)
  }

  if (reconnectAttempts.value < maxReconnectAttempts) {
    reconnectAttempts.value++
    const delay = Math.min(1000 * Math.pow(2, reconnectAttempts.value), 30000)
    console.log(
      `将在 ${delay / 1000} 秒后尝试第 ${reconnectAttempts.value}/${maxReconnectAttempts} 次重连`
    )

    reconnectTimeout.value = setTimeout(() => {
      if (!isConnected.value) {
        ElMessage.warning(
          `正在尝试重新连接... (${reconnectAttempts.value}/${maxReconnectAttempts})`
        )
        connectWebSocket()
      }
    }, delay)
  } else {
    ElMessage.error('重连次数已达上限，请刷新页面重试')
  }
}
// 获取用户ID
const getId = async () => {
  try {
    const response = await api.post('/id')
    console.log('response', response)

    userStore.userId = response.data.data
  } catch (error) {
    console.error('获取用户ID失败:', error)
    ElMessage.error('获取用户ID失败')
  }
}
// 建立WebSocket连接
const connectWebSocket = () => {
  // 确保没有旧的连接
  if (wsConnection.value) {
    wsConnection.value.close()
    wsConnection.value = null
  }

  // 清除旧的心跳定时器
  if (heartbeatInterval.value) {
    clearInterval(heartbeatInterval.value)
    heartbeatInterval.value = null
  }

  // 确保有用户ID
  if (!userStore.userId) {
    console.error('未找到用户ID，无法建立WebSocket连接')
    ElMessage.error('未找到用户ID，请刷新页面重试')
    return
  }

  const wsUrl = `ws://xvr8a0okpffe-7095.beijing-01.dayunet.com/ws?userId=${userStore.userId}`
  console.log('正在建立WebSocket连接:', wsUrl)

  try {
    wsConnection.value = new WebSocket(wsUrl)
  } catch (error) {
    console.error('创建WebSocket连接失败:', error)
    ElMessage.error('创建WebSocket连接失败，请检查网络连接')
    handleReconnect()
    return
  }

  wsConnection.value.onopen = () => {
    console.log('WebSocket连接成功')
    isConnected.value = true
    reconnectAttempts.value = 0
    ElMessage.success('已连接到聊天服务器')

    // 启动心跳机制
    heartbeatInterval.value = setInterval(sendHeartbeat, 30000) // 每30秒发送一次心跳
  }

  wsConnection.value.onmessage = (event) => {
    try {
      const data = JSON.parse(event.data)
      console.log('收到新消息:', data)

      // 处理心跳响应
      if (data.type === 'heartbeat') {
        console.log('收到心跳响应')
        return
      }

      // 处理用户发送的消息
      if (data.senderType === 'user') {
        updateUserMessageCount(data.fromUserId)
        messages.value.push({
          user: data.fromUserName || '未知用户',
          text: data.content,
          sentByUser: false,
          timestamp: new Date().toISOString()
        })
      } else {
        console.log('忽略消息：非用户发送的消息', data)
      }
    } catch (error) {
      console.error('处理消息失败:', error)
    }
  }

  wsConnection.value.onclose = (event) => {
    console.log('WebSocket连接关闭', event)
    isConnected.value = false
    clearInterval(heartbeatInterval.value)
    heartbeatInterval.value = null

    // 根据关闭代码处理不同的情况
    switch (event.code) {
      case 1000: // 正常关闭
        console.log('WebSocket连接正常关闭')
        break
      case 1006: // 非正常关闭
        console.error('WebSocket连接异常关闭')
        handleReconnect()
        break
      case 1011: // 服务器内部错误
        console.error('服务器内部错误，尝试重新连接')
        handleReconnect()
        break
      default:
        console.error(`WebSocket连接关闭，代码: ${event.code}`)
        handleReconnect()
    }
  }

  wsConnection.value.onerror = (error) => {
    console.error('WebSocket错误:', error)
    ElMessage.error('聊天服务器连接错误')
    handleReconnect()
  }
}

// 在组件挂载时获取团队成员数据
onMounted(async () => {
  await getId()
  try {
    const response = await api.post('/alluser')
    console.log('API响应:', response.data)

    if (response.data && Array.isArray(response.data.data)) {
      teamMembers.value = response.data.data.map((member) => ({
        id: member.id,
        name: member.username
      }))
    } else {
      throw new Error('未能正确解析用户数据')
    }

    // 建立WebSocket连接
    connectWebSocket()
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败，请检查网络或联系管理员')
  }
})

// 组件卸载时关闭WebSocket连接
onUnmounted(() => {
  if (reconnectTimeout.value) {
    clearTimeout(reconnectTimeout.value)
  }
  if (heartbeatInterval.value) {
    clearInterval(heartbeatInterval.value)
    heartbeatInterval.value = null
  }
  if (wsConnection.value) {
    wsConnection.value.close(1000, '组件卸载')
    wsConnection.value = null
  }
})

// 处理全选
const handleSelectAll = (val) => {
  if (val) {
    selectedMemberIds.value = teamMembers.value.map((member) => member.id)
  } else {
    selectedMemberIds.value = []
  }
}

// 修改发送消息的函数
const sendMessage = async () => {
  if (!newMessage.value.trim()) return

  // 如果没有选择任何用户，显示提示
  if (selectedMemberIds.value.length === 0) {
    ElMessage({
      type: 'warning',
      message: '请至少选择一个接收成员',
      duration: 3000
    })
    return
  }

  try {
    const response = await api.post('/broadcastselect', {
      uIds: selectedMemberIds.value,
      contents: newMessage.value
    })

    if (response.data.code === 200) {
      ElMessage({
        type: 'success',
        message: response.data.message || '发送成功',
        duration: 3000
      })

      // 添加到本地消息列表
      messages.value.push({
        user: '我',
        text: newMessage.value,
        sentByUser: true,
        timestamp: new Date().toISOString()
      })

      // 清空输入框
      newMessage.value = ''
    } else {
      ElMessage.error('发送失败：' + response.data.message)
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送消息失败，请重试')
  }
}

// 监听 selectedMemberIds 变化，更新全选状态
watch(selectedMemberIds, (newVal) => {
  // 如果选中的人数和总人数相等，则全选
  if (newVal.length === teamMembers.value.length) {
    selectAll.value = true
  } else {
    selectAll.value = false
  }
})
</script>

<template>
  <div class="message-container">
    <div class="page-header">
      <h1>消息中心</h1>
      <div class="connection-status">
        <el-tag :type="isConnected ? 'success' : 'danger'" effect="dark">
          {{ isConnected ? '已连接' : '未连接' }}
        </el-tag>
      </div>
    </div>

    <el-card class="message-card" shadow="hover">
      <!-- 添加成员选择区域 -->
      <div class="member-selection">
        <div class="selection-header">
          <h3>选择接收成员</h3>
          <div class="selection-controls">
            <el-checkbox
              v-model="selectAll"
              @change="handleSelectAll"
              id="selectAll"
            >
              全选
            </el-checkbox>
            <span class="selected-count">
              已选择 {{ selectedMemberIds.length }} 人
            </span>
          </div>
        </div>

        <div class="search-box">
          <el-input
            v-model="searchQuery"
            placeholder="搜索成员..."
            prefix-icon="Search"
            clearable
          />
        </div>

        <div class="member-list">
          <el-checkbox-group v-model="selectedMemberIds">
            <div
              v-for="member in filteredTeamMembers"
              :key="member.id"
              class="member-item"
              :class="{
                'member-selected': selectedMemberIds.includes(member.id)
              }"
            >
              <el-checkbox :label="member.id">
                <div class="member-info">
                  <el-avatar :size="32" class="member-avatar">
                    {{ member.name.charAt(0).toUpperCase() }}
                  </el-avatar>
                  <span class="member-name">{{ member.name }}</span>
                  <div
                    class="message-indicator"
                    v-if="userMessageCounts[member.id]"
                  >
                    <el-badge
                      :value="userMessageCounts[member.id]"
                      type="danger"
                    />
                  </div>
                </div>
              </el-checkbox>
            </div>
          </el-checkbox-group>
        </div>
      </div>

      <div class="messages-wrapper">
        <div class="messages-list" v-if="messages.length > 0">
          <div
            class="message"
            v-for="(message, index) in messages"
            :key="index"
            :class="{
              'message-sent': message.sentByUser,
              'message-received': !message.sentByUser
            }"
          >
            <div class="message-content">
              <div class="message-header">
                <strong>{{ message.user }}</strong>
                <span class="message-time">
                  {{ new Date(message.timestamp).toLocaleString() }}
                </span>
              </div>
              <div class="message-text">{{ message.text }}</div>
            </div>
          </div>
        </div>
        <div class="no-messages" v-else>
          <p>暂无消息记录</p>
        </div>
      </div>

      <div class="chat-input">
        <el-input
          v-model="newMessage"
          type="text"
          placeholder="输入消息..."
          @keyup.enter="sendMessage"
          maxlength="500"
          show-word-limit
          :disabled="!isConnected"
        />
        <el-button
          @click="sendMessage"
          type="primary"
          class="send-button"
          :disabled="!newMessage.trim() || !isConnected"
        >
          <el-icon><Promotion /></el-icon>
          <span>发送</span>
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.message-container {
  padding: 40px;
  background: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  margin-bottom: 40px;

  h1 {
    font-size: 32px;
    font-weight: 600;
    color: #333;
    margin: 0;
    background: linear-gradient(135deg, #333 0%, #555 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    letter-spacing: 0.5px;
  }
}

.message-card {
  border-radius: 20px;
  overflow: hidden;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
  transition: all 0.3s;
  background: white;
  padding: 32px;
  margin-bottom: 40px;

  &:hover {
    box-shadow: 0 12px 32px rgba(0, 0, 0, 0.12);
    transform: translateY(-3px);
  }
}

.member-selection {
  margin-bottom: 36px;
  padding: 24px;
  border-radius: 16px;
  background-color: #f9fafb;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);

  .selection-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 20px;
    border-bottom: 1px solid #eaedf0;

    h3 {
      font-size: 20px;
      font-weight: 600;
      color: #333;
      margin: 0;
    }
  }

  .search-box {
    margin-bottom: 20px;

    :deep(.el-input__wrapper) {
      border-radius: 20px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }
  }
}

.member-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
  padding: 20px;
  max-height: 400px;
  overflow-y: auto;
}

.member-item {
  background: #fff;
  border-radius: 8px;
  padding: 12px;
  transition: all 0.3s ease;
  border: 1px solid #ebeef5;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  }

  &.member-selected {
    background: rgba(103, 126, 234, 0.05);
    border-color: #667eea;
  }
}

.member-info {
  display: flex;
  align-items: center;
  gap: 12px;
  width: 100%;

  .member-name {
    flex: 1;
  }

  .message-indicator {
    margin-left: auto;
  }
}

.member-avatar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.member-name {
  font-size: 14px;
  color: #333;
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.selection-controls {
  display: flex;
  align-items: center;
  gap: 16px;
}

.selected-count {
  font-size: 14px;
  color: #409eff;
}

.messages-wrapper {
  margin-bottom: 28px;
  height: 350px;
  overflow-y: auto;
  padding: 20px;
  border-radius: 16px;
  background-color: #f9fafb;
  box-shadow: inset 0 2px 8px rgba(0, 0, 0, 0.05);
}

.messages-list {
  display: flex;
  flex-direction: column;
  gap: 18px;
}

.message {
  padding: 18px;
  border-radius: 14px;
  max-width: 85%;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  word-break: break-word;
  transition: all 0.3s;

  &:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    transform: translateY(-2px);
  }

  .message-header {
    margin-bottom: 10px;
    font-size: 14px;
  }

  .message-text {
    font-size: 16px;
    line-height: 1.6;
  }
}

.message-sent {
  background: linear-gradient(135deg, #e0f7fa 0%, #e3f2fd 100%);
  margin-left: auto;
  border-bottom-right-radius: 2px;

  .message-header {
    color: #0277bd;
  }
}

.message-received {
  background: white;
  margin-right: auto;
  border-bottom-left-radius: 2px;

  .message-header {
    color: #455a64;
  }
}

.no-messages {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #90a4ae;
  font-size: 17px;
  font-style: italic;
}

.chat-input {
  display: flex;
  gap: 20px;

  :deep(.el-input__wrapper) {
    border-radius: 14px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    padding: 6px 18px;
  }

  :deep(.el-input__inner) {
    height: 50px;
    font-size: 16px;
    color: #333;
  }

  .send-button {
    border-radius: 14px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
    padding: 0 32px;
    transition: all 0.3s;
    font-size: 17px;
    height: 50px;

    .el-icon {
      margin-right: 10px;
      font-size: 18px;
    }

    &:hover {
      transform: translateY(-4px);
      box-shadow: 0 8px 20px rgba(102, 126, 234, 0.25);
      opacity: 0.95;
    }

    &:active {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
    }
  }
}

:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #667eea;
  border-color: #667eea;
  transition: all 0.3s ease;
}

:deep(.el-checkbox__input.is-checked + .el-checkbox__label) {
  color: #333;
  font-weight: 500;
}

:deep(.el-checkbox__inner:hover) {
  border-color: #667eea;
}

:deep(.el-checkbox__input.is-focus .el-checkbox__inner) {
  border-color: #667eea;
}

:deep(.el-checkbox) {
  transform: scale(1.1);
  margin-right: 5px;

  &.is-checked {
    .el-checkbox__label {
      color: #333;
      font-weight: 500;
    }
  }
}

.select-all {
  :deep(.el-checkbox) {
    transform: scale(1.15);

    .el-checkbox__inner {
      width: 18px;
      height: 18px;
      transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);

      &::after {
        height: 9px;
        width: 4px;
        left: 6px;
      }
    }

    .el-checkbox__label {
      font-size: 16px;
      font-weight: 600;
      transition: all 0.3s ease;
    }

    &.is-checked {
      .el-checkbox__inner {
        transform: scale(1.08);
        box-shadow: 0 2px 6px rgba(102, 126, 234, 0.25);
      }

      .el-checkbox__label {
        color: #667eea;
      }
    }
  }
}

.connection-status {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}

.message-time {
  font-size: 12px;
  color: #909399;
  margin-left: 8px;
}
</style>
